package com.jianyun.jyzs.utils;


import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;


import com.alibaba.fastjson.JSON;
import com.jianyun.jyzs.activity.SetMyProfileActivity;
import com.jianyun.jyzs.bean.MeUserInfo;
import com.jianyun.jyzs.http.Api;
import com.jianyun.jyzs.http.FileRequestBody;
import com.jianyun.jyzs.http.RetrofitHelper;
import com.jianyun.jyzs.widget.BottomMenuDialog;
import com.jianyun.jyzs.widget.LoadingDialog;

import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.rongcloud.rce.lib.RceErrorCode;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class UploadPortraitUtil {


    private Context context;
    public LoadingDialog loadingDialog;
    private PhotoUtils photoUtils;
    private BottomMenuDialog dialog;
    private onUploadPortraitListener uploadPortraitListener;
    private OnFileUploadListener onFileUploadListener;

    public UploadPortraitUtil(Context context, LoadingDialog loadingDialog) {
        this.context = context;
        this.loadingDialog = loadingDialog;
        setPortraitChangeListener();
    }


    private void setPortraitChangeListener() {
        photoUtils = new PhotoUtils(new PhotoUtils.OnPhotoResultListener() {
            @Override
            public void onPhotoResult(final Uri thumbUrl, final Uri largeUrl) {
                if (largeUrl != null && !TextUtils.isEmpty(largeUrl.getPath())) {
                    File largeImageFile = new File(largeUrl.getPath());
                    Log.i("test", "上传图片图片：" + largeUrl.getPath() + "\n" + largeImageFile.getName());
                    uploadProtrait(largeImageFile);

                } else {
                    if (uploadPortraitListener != null) {
                        uploadPortraitListener.onUploadFailed("错误");
                    }
                }
            }

            @Override
            public void onPhotoCancel() {

            }
        });
    }

    //上传图片到OA服务器
    public void uploadProtrait(File file) {
        HashMap<String, RequestBody> map = new HashMap<>();
        Api api = RetrofitHelper.builderErpRoot2().create(Api.class);
        String enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        String userId = LoginCache.getInstance().getUserInfo().getUserId();
        String name = LoginCache.getInstance().getUserDetaileInfo().getName();
        final String iconPathId = LoginCache.getInstance().getUserDetaileInfo().getIconPathId();
        map.put("method", RequestBody.create(MediaType.parse("text/plain"), "UpdateEmail"));
        map.put("enterpriseCode", RequestBody.create(MediaType.parse("text/plain"), enterpriseCode));
        map.put("FolderID", RequestBody.create(MediaType.parse("text/plain"), iconPathId));
        map.put("FolderName", RequestBody.create(MediaType.parse("text/plain"), "sys_qx_employee"));
        map.put("FileName", RequestBody.create(MediaType.parse("text/plain"), file.getName()));
        map.put("employeeId", RequestBody.create(MediaType.parse("text/plain"), userId));
        map.put("employeeName", RequestBody.create(MediaType.parse("text/plain"), name));
        map.put("BusinessClass", RequestBody.create(MediaType.parse("text/plain"), "员工基本信息表"));
        map.put("appCode", RequestBody.create(MediaType.parse("text/plain"), "jyzs"));
        map.put("appType", RequestBody.create(MediaType.parse("text/plain"), "Android"));
        map.put("appVersion", RequestBody.create(MediaType.parse("text/plain"), "1.0.2"));
        FileRequestBody fileRequestBody = new FileRequestBody(file, null);
        api.upOaProfile(map, MultipartBody.Part.createFormData("filedata", file.getName(), fileRequestBody))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onCompleted() {
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onNext(Object o) {
                        String s = JSON.toJSONString(o);
                        Log.i("test", "头像提交成功：" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String iconPath = jsonObject.getString("iconPath");
                            //截取
                            //String substring = iconPath.substring(iconPath.indexOf("?") + 1, iconPath.length());
                            //保存
                            MeUserInfo userDetaileInfo = LoginCache.getInstance().getUserDetaileInfo();
                            userDetaileInfo.setIconPaths(iconPath);
                            LoginCache.getInstance().setUserDetaileInfo(userDetaileInfo);
                            uploadPortraitListener.onUploadSuccess("", iconPath);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        loadingDialog.dismiss();

                    }
                });
    }


    public void showPhotoDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }

        dialog = new BottomMenuDialog(context);
        dialog.setConfirmListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                String[] permissions = {Manifest.permission.CAMERA};
                if (!PermissionCheckUtil.requestPermissions((Activity) context, permissions)) {
                    return;
                }
                photoUtils.takePicture((Activity) context);
            }
        });
        dialog.setMiddleListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
                if (!PermissionCheckUtil.requestPermissions((Activity) context, permissions)) {
                    return;
                }
                photoUtils.selectPicture((Activity) context);
            }
        });
        dialog.show();
    }

    public PhotoUtils getPhotoUtils() {
        return photoUtils;
    }

    public Uri getUploadFileUri() {
        return getPhotoUtils().getUploadFileUri();
    }

    public void setUploadFileUri(Uri uri) {
        getPhotoUtils().setUploadFileUri(uri);
    }

    public void setUploadPortraitListener(onUploadPortraitListener listener) {
        uploadPortraitListener = listener;
    }

    public interface onUploadPortraitListener {
        void onUploadSuccess(String thumbUrl, String largeUrl);

        void onUploadFailed(String msg);
    }

    public interface OnFileUploadListener {
        void setupFileSuccess(boolean isUploadFile);
    }

    void setOnFileUpload(OnFileUploadListener onFileUpload) {
        this.onFileUploadListener = onFileUpload;
    }
}
